/*
 * FilePath     : \src\utils\arraySort.ts
 * Author       : SJZ
 * Date         : 2025-03-12 19:28
 * LastEditors  : SJZ
 * LastEditTime : 2025-03-12 20:04
 * Description  : 集合排序
 * CodeIterationRecord: 
 */

/**
 * 按照指定的各个key自定义升降的排序
 *     demo：sortByKeys(arr, ['sex', "age", "class", "height"], [1, 0, 0, 1]);
 *     说明：集合按照sex升序，age降序，class降序，height升序进行排序
 * @param arr 数据源
 * @param keys 排序的key
 * @param isAscend 默认为全升序(1为升序，0为降序)
 * @returns
 */
export const sortByKeys = <T>(arr: T[], keys: string[], isAscend?: number[]): void => {
  let keyLen = keys.length;
  if (keyLen <= 0) {
    console.error("排序keys为空！");
    return;
  }
  let newAscend: number[] = [];
  if (!isAscend) {
    for (let i: number = 0; i < keyLen; i++) {
      newAscend.push(1);
    }
  } else {
    newAscend = isAscend;
  }
  if (keyLen != newAscend.length) {
    console.error("排序keys和排序规则数量不一致！");
    return;
  }
  arr.sort((arr1: any, arr2: any) => {
    for (let idxer: number = 0; idxer < keys.length; idxer++) {
      let key = keys[idxer];
      let arr1Value = arr1[key];
      let arr2Value = arr2[key];
      if (arr1Value === arr2Value) {
        continue;
      } else {
        let isAsc = newAscend[idxer];
        return isAsc ? arr1Value - arr2Value : arr2Value - arr1Value;
      }
    }
    return 0;
  });
};
